package cn.shiva.jwt.controller;

import cn.shiva.jwt.basic.IgnoreJwt;
import cn.shiva.jwt.basic.Result;
import io.jsonwebtoken.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shiva   2021/11/12 20:25
 */
@RestController
public class LoginController {

    // 准备密钥
    public static final String SECRET = "S@&op@!@.S5!)(@{";

    @IgnoreJwt
    @RequestMapping("login")
    public Result<Object> login(String username, String password) {
        if (!"admin".equals(username) || !"admin".equals(password)) {
            return Result.builder().code(1).message("用户名或密码错误").build();
        }
        // 准备 负载数据
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", 1);
        payload.put("username", username);
        payload.put("roles", new String[]{"admin", "test"});
        payload.put("loginTime", System.currentTimeMillis());

        // 组装 JWT 令牌
        String jwt = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setClaims(payload)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 30 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();

        return Result.builder().code(0).message("登录成功").data(jwt).build();
    }

    @IgnoreJwt
    @RequestMapping("confirmJwt")
    public Result<Object> confirmJwt(HttpServletRequest request) {
        String jwt = request.getHeader("Authorization");
        try {
            // 验证
            Claims body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(jwt).getBody();
            System.out.println(body.getIssuedAt());
            System.out.println(body.getExpiration());
            System.out.println(body.get("roles"));
            return Result.builder().code(0).message("校验成功").data(body.toString()).build();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            return Result.builder().code(1).message("JWT 过期").build();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
            return Result.builder().code(1).message("非正常 JWT ").build();
        } catch (SignatureException e) {
            e.printStackTrace();
            return Result.builder().code(1).message("JWT签名不匹配").build();
        }
        return Result.builder().code(1).message("验证出错").build();
    }

    @RequestMapping("sensitive")
    public Result<Object> sensitive() {
        return Result.builder().code(0).message("请求成功").data("返回敏感信息").build();
    }

}
